//
//  userViewModel.swift
//  weibo1
//
//  Created by 李进 on 15/10/20.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit
import Foundation
import SDWebImage

class userFLViewModel{
    
    //含有一个数组来装模型数组
    lazy var userFriendM = [userFriendViewModel]()
    
    func loadUserFm(isPull:Bool ,finished: (isSuccessed: Bool)->()){
        
        //定义since_id和max_id ispull 是用来判断是上拉刷新还是下拉刷新
        let since_id = isPull ? 0 : (userFriendM.first?.status.id ?? 0)
        
        let max_id = isPull ? (userFriendM.last?.status.id ?? 0) : 0
        
        //下载数据

        UserDAL.loadUser(since_id, max_id: max_id) { (temparray) -> () in
            
            guard let array = temparray else  {
                finished(isSuccessed: false)
                
                return
            }
            
            //在这之前就把数据返回并且做了判断。所以保存数据在这边是比较合适的
            //UserDAL.saveDataBySqlite(array)
            //便利数组，创建一个可变数组
            var arrayList = [userFriendViewModel]()
            
            //便利数组
            for dict in array {
                
                arrayList.append(userFriendViewModel(status: userFriendesModel(dict: dict)))
                //print(arrayList.last?.status.text)
            }
 
            //判断是否是上拉刷新
            if max_id > 0 {
                self.userFriendM += arrayList
            }else{
                
                self.userFriendM = arrayList + self.userFriendM
            }
            //print(self.userFriendM.count)
            //下载图片
            cacheSingleImage(arrayList, finished: finished)
        }

        }
    }

    /// 缓存单张图片（混存单张图片，是将下载好的单张图片使用多线程知识来完成，创建调度组／入组／出组／最好呦通知回实时监控调度组是否完成）
    ///
    /// - parameter arrayList: 数组
    /// - parameter finished:  完成回调
    func cacheSingleImage(arrayList:[userFriendViewModel], finished: (isSuccessed: Bool)->()){
        
        
        var dateLenght = 0
        
        //创建调度组
        let group = dispatch_group_create()
        
        //便利数组
        for vm in arrayList{
            
            if vm.thumbnailUrls!.count != 1 {
                continue
            }
            
            //获取url 
            let url = vm.thumbnailUrls![0]
            //print(url)
            
            //入组
            dispatch_group_enter(group)
            
            //下载图片
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [],
                progress: nil, completed: { (image, _, _, _, _) -> Void in
                    
                    if let img = image , let data = UIImagePNGRepresentation(img){
                        
                        dateLenght += data.length
                    }
                    //出组
                    dispatch_group_leave(group)
            })
        }
        //监听调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存完成+ \(dateLenght / 1024) k")
            finished(isSuccessed: true)
        }
        
    }
    
